import React, { Component } from 'react'
import { TouchableOpacity } from 'react-native'
import FontAwesome from 'react-native-vector-icons/FontAwesome'
import { PropTypes } from 'prop-types'

export default class BaseItem extends Component {
	static propsTypes = {
		projectModel: PropTypes.object,
		onSelect: PropTypes.func,
		onFavorite: PropTypes.func
	}

	constructor(props) {
		super(props)
		this.state = {
			isFavorite: this.props.projectModel.isFavorite
		}
	}

	/**
	 * componentWillReceiveProps在新版React中不能再用了
	 * @param nextProps
	 * @param preState
	 */
	static getDerivedStateFromProps(nextProps, preState) {
		const isFavorite = nextProps.projectModel.isFavorite
		if (preState.isFavorite !== isFavorite) {
			return {
				isFavorite: isFavorite
			}
		}
		return null
	}

	setFavoriteState(isFavorite) {
		this.props.projectModel.isFavorite = isFavorite
		this.setState({
			isFavorite: isFavorite
		})
	}

	//详情页面修改收藏的状态之后同步到前面的页面，前面的页面不需要刷新
	onItemClick() {
		this.props.onSelect(isFavorite => {
			this.setFavoriteState(isFavorite)
		})
	}

	onPressFavorite() {
		this.setFavoriteState(!this.state.isFavorite)
		this.props.onFavorite(
			this.props.projectModel.item,
			!this.state.isFavorite
		)
	}

	_favoriteIcon() {
		return (
			<TouchableOpacity
				style={{ padding: 6 }}
				underlayColor={'transparent'}
				onPress={() => this.onPressFavorite()}
			>
				<FontAwesome
					name={this.state.isFavorite ? 'star' : 'star-o'}
					size={26}
					style={{ color: '#678' }}
				/>
			</TouchableOpacity>
		)
	}
}
